<template>
  <treeselect v-model="val"
              :options="options"
              :show-count="showCount"
              :placeholder="placeholder"
              :disabled="readonly"
              :multiple="multiple" />
</template>

<script>
import {treeselectFolder} from "../../../api/am/amFolder";
import Treeselect from "@riophae/vue-treeselect";
import {isNull} from "lodash";
import {isValueExist, treeFind} from "../../../utils/tools";

export default {
  components: {Treeselect},
  props: {
    value: [String, Number],
    showCount: {
      type: Boolean,
      default: true
    },
    readonly: Boolean,
    multiple: Boolean,
    placeholder: {
      type: String,
      default: '请选择文件夹'
    }
  },
  data() {
    return {
      options: [],
      val: null
    }
  },
  watch: {
    value: {
      handler(v) {
        if(isValueExist(v) && isNull(this.val)) {
          this.val = v
        }
      },
      immediate: true
    },
    val: {
      handler(v) {
        if(isValueExist(v) && this.val !== this.value) {
          const target = treeFind(this.options, node => node.id === v)
          this.$emit('input', v)
          this.$emit('select', target)
        }
      },
      immediate: true
    }
  },
  created() {
    treeselectFolder().then(response => {
      this.options = response.data;
      if(isNull(this.val)) {
        this.val = this.options[0].id
      }
    })
  }
}
</script>

<style></style>
